import axios, { AxiosError, AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';

import { ElMessage } from 'element-plus';
// 移除 qs 依赖
// import qs from 'qs'
import { config } from '@/config/axios/config';

const { base_url, request_timeout } = config;

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: base_url, // api 的 base_url
  timeout: request_timeout, // 请求超时时间
  withCredentials: false, // 禁用 Cookie 等信息
});

// 简单的查询字符串处理函数，替代 qs 库
const stringifyParams = (params: Record<string, any>): string => {
  return Object.keys(params)
    .filter(key => params[key] !== undefined && params[key] !== null)
    .map(key => {
      const value = params[key];
      return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
    })
    .join('&');
};

// request拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const params = config.params || {};
    const data = config.data || false;

    // 自动为所有请求添加workshopId参数，但仅当URL中有workshopId参数时
    const workshopId = getWorkshopIdFromUrl();
    if (workshopId) {
      if (config.method?.toUpperCase() === 'GET') {
        // 为GET请求添加workshopId
        params.workshopId = workshopId;
      } else if (data && typeof data === 'object' && !Array.isArray(data)) {
        // 为POST请求添加workshopId
        (data as any).workshopId = workshopId;
      }
    }

    if (
      config.method?.toUpperCase() === 'POST' &&
      ((config.headers || {}) as any)['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      // 使用自定义函数替代 qs.stringify
      config.data = stringifyParams(data as Record<string, any>);
    }
    // get参数编码
    if (config.method?.toUpperCase() === 'GET' && params) {
      config.params = params;
    }
    return config;
  },
  (error: AxiosError) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 从URL获取workshopId的辅助函数
function getWorkshopIdFromUrl(): string | null {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get('workshopId');
}

// response 拦截器
service.interceptors.response.use(
  async (response: AxiosResponse<any>) => {
    const { data } = response;
    if (!data) {
      throw new Error('请求没有返回值');
    }

    // 二进制数据则直接返回，例如说 Excel 导出
    if (
      response.request.responseType === 'blob' ||
      response.request.responseType === 'arraybuffer'
    ) {
      if (response.data.type !== 'application/json') {
        return response.data;
      }
      return await new Response(response.data).json();
    }

    // 简化的响应处理
    return data;
  },
  (error: AxiosError) => {
    console.log('请求错误:', error);
    let { message } = error;
    if (message === 'Network Error') {
      message = '网络错误，请检查您的网络连接';
    } else if (message.includes('timeout')) {
      message = '请求超时，请稍后重试';
    } else if (message.includes('Request failed with status code')) {
      message = '请求失败，状态码：' + message.substr(message.length - 3);
    }
    ElMessage.error(message);
    return Promise.reject(error);
  }
);

export { service };
